package com.cuc.authserver.dao;

import com.cuc.authserver.model.MyPermissionDetails;
import com.cuc.authserver.model.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    //根据账号查询用户信息
    public MyUserDetails getUserByUsername(String username){
        String sql = "select user_id,user_name,password from sys_user where user_name = ?";
        //连接数据库查询用户
        List<MyUserDetails> list = jdbcTemplate.query(sql, new Object[]{username},
                new BeanPropertyRowMapper<>(MyUserDetails.class));
        if(list !=null && list.size()==1){
            return list.get(0);
        }
        return null;
    }

    public List<String> findPermissionsByUserId(Long userId){
        //String sql = "SELECT * FROM sys_user WHERE user_id = ?";
        String sql = "select ur.user_id, ur.role_id, r.role_key from sys_user_role ur left join sys_role r on ur" +
                ".role_id = r.role_id where user_id = ?";

        List<MyPermissionDetails> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(MyPermissionDetails.class));
        List<String> permissions = new ArrayList<>();
        list.forEach(c -> permissions.add(c.getRole_key()));
        return permissions;
    }


}
